/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 *
 *AppAreaInitializationConfigController
 * 区域初始化配置
 *
 * 修改纪录
 * 2022-12-23 版本：1.0 wuyuyang 创建。
 * @version 版本：1.0
 * @author 作者：wuyuyang
 * 创建日期：2022-12-23
 */

package com.topscomm.appv2.controller;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.topscomm.appv2.SystemConst;
import com.topscomm.appv2.pojo.AppAreaInitializationConfigEntity;
import com.topscomm.appv2.service.impl.AppUserUseInfoService;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboModuleEntity;
import com.topscomm.cbo.service.ICboModuleService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.topscomm.appv2.controller.auto.AppAreaInitializationConfigControllerAuto;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: wuyuyang
 * @date: 2022-12-23
 * @description:区域初始化配置Controller
 * @modify:
 */
@RestController
@RequestMapping("appv2/appAreaInitializationConfig")
public class AppAreaInitializationConfigController extends AppAreaInitializationConfigControllerAuto implements IAppAreaInitializationConfigController {
    @Autowired
	private ICboModuleService cboModuleService;
    @Autowired
    private AppUserUseInfoService appUserUseInfoService;

	/**
	 * @author: wuyuyang
	 * @date: 2022-12-23
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_areacode")) {
			String value = paraMap.get("qry_areacode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and areacode = '{0}' ", value);
		}
		return sql.toString();
	}



	/**
	 *
	 * @description:  重写dataCodeList方法
	 * @param paraMap
	 * @return
	 * @author: wuyuyang
	 * @date: 2022-12-23
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		ResponseResult<Object> responseResult = super.dataCodeList(paraMap);
		Map<String,Object> codeMap  = (Map<String, Object>) responseResult.getResult();
		// 查询一级目录
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("code like '80%' and  extendfield2 = '{0}' and code != '80' and enabled = {1} and parentid = (select id from cbomodule where code = '80') order by code asc", SystemConst.SELECT_FIRST_DIRECTION, SystemConst.Enabled_Yes);
		List<Map<String, Object>> firstDirectoryList = cboModuleService.queryMapByWhere(sql.toString());
		codeMap.put("firstDirectoryList", firstDirectoryList);
		// 查询文档中心
		sql.clear();
		sql.appendSingle("code like '8099%' and  extendfield2 = '{0}' and code != '8099' and enabled = {1} and parentid = (select id from cbomodule where code = '8099')", SystemConst.SELECT_DOCUMENT_CENTER, SystemConst.Enabled_Yes);
		List<Map<String, Object>> documentCenterList = cboModuleService.queryMapByWhere(sql.toString());
		codeMap.put("documentCenterList", documentCenterList);
		return ResponseResult.ok(codeMap);
	}

	/**
	 * @author: wuyuyang
	 * @date: 2022-12-23
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * @Description:    发布已经保存的区域化记录
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           27/12/2022 下午7:18
	 * @Version:        1.0
	 **/
	@PutMapping(value = "/doPublish")
	public ResponseResult<Object> doPublish(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> dataMap = paraMap;
			beforeUpdate(dataMap, paraMap);
			this.service.update(dataMap);
			afterUpdate(dataMap, paraMap);
			return ResponseResult.ok(paraMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}


    /**
     * @Description:    根据参数查询app或一级目录   "0" 目录 ，"1" app
     * @Author:         wuyuyang
     * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date:           28/12/2022 下午5:46
     * @Version:        1.0
     **/
	@Transactional
	@GetMapping(value = "/queryModule")
	public ResponseResult<Object> queryModule (@RequestParam(required = false) Map<String, Object> paraMap) {
		    paraMap = BaseUtil.decodeSecureMap(paraMap);
		    Query query = new Query(paraMap);
		    query.setPageSize(9999);
			query.setSidx(CboModuleEntity.FieldCode);
		    List<Map<String, Object>> tempList = null;
		    String flag = ConvertUtil.convertToString(paraMap.get("flag"));
		    if(!StringUtils.isEmpty(flag)) {
		    	// 查询app模块
		    	if(SystemConst.SELECT_APP.equals(flag)){
					tempList = appUserUseInfoService.queryOpenedModule(paraMap);
					int totalCount = tempList.size();
					Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
					return ResponseResult.ok(page);
				}
		    	// 查询一级目录模块
				if(SystemConst.SELECT_FIRST_DIRECTION.equals(flag)){
					StringBufferProxy sql = new StringBufferProxy();
					sql.appendSingle("code like '80%' and  extendfield2 = '{0}' and code != '80' and enabled = {1} and parentid = (select id from cbomodule where code = '80')",SystemConst.SELECT_FIRST_DIRECTION, SystemConst.Enabled_Yes);
					// 组件上方搜索框
					if(paraMap.containsKey("qry_code") && !StringUtils.isEmpty(ConvertUtil.convertToString(paraMap.get("qry_code")))){
						sql.appendSingle(" and code = '{0}'",ConvertUtil.convertToString(paraMap.get("qry_code")));
					}
					if(paraMap.containsKey("qry_name") && !StringUtils.isEmpty(ConvertUtil.convertToString(paraMap.get("qry_name")))){
						sql.appendSingle(" and name like '%{0}%'",ConvertUtil.convertToString(paraMap.get("qry_name")));
					}
					int totalCount = cboModuleService.getCount(sql.toString());
					if (query.getPageSize() > 0) {
						tempList = cboModuleService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
								query.getSidx(), query.getSord());
					} else {
						tempList = cboModuleService.queryMapByWhere(sql.toString());
					}
					Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
					return ResponseResult.ok(page);
				}
				// 查询文档中心模块
				if(SystemConst.SELECT_DOCUMENT_CENTER.equals(flag)){
					StringBufferProxy sql = new StringBufferProxy();
					sql.appendSingle("code like '8099%' and  extendfield2 = '{0}' and code != '8099' and enabled = {1} and parentid = (select id from cbomodule where code = '8099')", SystemConst.SELECT_DOCUMENT_CENTER, SystemConst.Enabled_Yes);
					// 组件上方搜索框
					if(paraMap.containsKey("qry_code") && !StringUtils.isEmpty(ConvertUtil.convertToString(paraMap.get("qry_code")))){
						sql.appendSingle(" and code = '{0}'",ConvertUtil.convertToString(paraMap.get("qry_code")));
					}
					if(paraMap.containsKey("qry_name") && !StringUtils.isEmpty(ConvertUtil.convertToString(paraMap.get("qry_name")))){
						sql.appendSingle(" and name like '%{0}%'",ConvertUtil.convertToString(paraMap.get("qry_name")));
					}
					int totalCount = cboModuleService.getCount(sql.toString());
					if (query.getPageSize() > 0) {
						tempList = cboModuleService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
								query.getSidx(), query.getSord());
					} else {
						tempList = cboModuleService.queryMapByWhere(sql.toString());
					}
					Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
					return ResponseResult.ok(page);
				}
			}
		    // 选中模块数据回显
		    if(paraMap.containsKey("qry_codelist") && !StringUtils.isEmpty(ConvertUtil.convertToString(paraMap.get("qry_codelist")))){
				StringBufferProxy sql = new StringBufferProxy();
				String res = "";
				// 查询参数分解
				String[] qry_codelists = ConvertUtil.convertToString(paraMap.get("qry_codelist")).split(",");
				ArrayList<String> codelist = new ArrayList<String>(Arrays.asList(qry_codelists));
				for(String code : codelist) {
					res += "'" + code + "'" + ",";
				}
				res = res.substring(0, res.length()-1);
				sql.appendSingle("code in ({0})", res);
				int totalCount = cboModuleService.getCount(sql.toString());
				if (query.getPageSize() > 0) {
					tempList = cboModuleService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
							query.getSidx(), query.getSord());
				} else {
					tempList = cboModuleService.queryMapByWhere(sql.toString());
				}
				Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
				return ResponseResult.ok(page);
			}
		    return ResponseResult.error("参数错误");
	}


    @Override
	protected void beforeUpdate(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		// 获取最大数
		String maxNum = ConvertUtil.convertToString(dataMap.get(AppAreaInitializationConfigEntity.FieldMaxnum));
		// 获取默认值
		String defaultvalue = ConvertUtil.convertToString(dataMap.get(AppAreaInitializationConfigEntity.FieldDefaultvalue));
		// 获取默认值的code
		String defaultvalueNo = ConvertUtil.convertToString(dataMap.get(AppAreaInitializationConfigEntity.FieldExtendfield1));
		// 默认值的name
		String defaultvalueName = ConvertUtil.convertToString(dataMap.get(AppAreaInitializationConfigEntity.FieldExtendfield2));
		if(!StringUtils.isEmpty(maxNum) && !StringUtils.isEmpty(defaultvalue)) {
			// 字符串转为JSONArray，默认值小于json数组大小时截取默认值
			JSONArray defaultvalueJsonArray = JSONArray.parseArray(defaultvalue);
			JSONArray newDefaultvalueJsonArray = new JSONArray();
			if(ConvertUtil.convertToInt(maxNum) < defaultvalueJsonArray.size()) {
				int maxNum1 = ConvertUtil.convertToInt(maxNum);
				String newDefaultvalueNo = "";
				String newDefaultvalueName = "";
				// 将字符串数组转为list
				ArrayList<String> defaultvalueNoList = new ArrayList<String>(Arrays.asList(defaultvalueNo.split(","))) ;
				ArrayList<String> defaultvalueNameList= new ArrayList<String>(Arrays.asList(defaultvalueName.split(","))) ;
				// 循环处理新JSONArray的值
				for(int i=0; i < maxNum1; i++){
					newDefaultvalueJsonArray.add(defaultvalueJsonArray.get(i));
					newDefaultvalueNo += defaultvalueNoList.get(i) + ",";
					newDefaultvalueName += defaultvalueNameList.get(i) + ",";
				}
				// 放入最终处理后的默认值的no和name
				dataMap.put(AppAreaInitializationConfigEntity.FieldExtendfield1, newDefaultvalueNo.substring(0, newDefaultvalueNo.length()-1));
				dataMap.put(AppAreaInitializationConfigEntity.FieldExtendfield2, newDefaultvalueName.substring(0, newDefaultvalueName.length()-1));
            	// 最终放入处理后的默认值
            	dataMap.put(AppAreaInitializationConfigEntity.FieldDefaultvalue, newDefaultvalueJsonArray.toString());
			}
		}
	}

	/**
	 * @Description:    用户信息表金刚区强制更新
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           2/1/2023 下午8:14
	 * @Version:        1.0
	 **/
	@Transactional
	@PutMapping(value = "/updateForceAppUserInfoCorearea")
	public ResponseResult<Object> updateForceAppUserInfoCorearea(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 先保存后更新
		try {
			Map<String, Object> dataMap = paraMap;
			this.service.update(dataMap);
			return ResponseResult.ok("ok");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
//		StringBufferProxy sql = new StringBufferProxy();
//		// 已经发布且有效的金刚区默认数据
//		sql.appendSingle("areacode = '{0}' and publish = {1} and enabled = {2}",
//				SystemConst.AppAreaType.corearea, SystemConst.PublishState, SystemConst.Enabled_Yes);
//		List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList = this.service.queryByWhere(sql.toString());
//		if(appAreaInitializationConfigEntityList.size() != 1){
//			throw new BusinessException("未找到金刚区发布数据");
//		}else{
//			// 处理用户信息表金刚区强制更新
//			boolean res = this.service.updateForceAppUserInfoCorearea(appAreaInitializationConfigEntityList, paraMap);
//			if(res == true){
//				return ResponseResult.ok("更新成功");
//			}
//		}
//		throw new BusinessException("更新失败");
	}


	/**
	 * @Description:    用户信息表金刚区最大数强制更新
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           2/1/2023 下午8:14
	 * @Version:        1.0
	 **/
	@Transactional
	@PutMapping(value = "/updateForceAppUserInfoCoreareaMaxnum")
	public ResponseResult<Object> updateForceAppUserInfoCoreareaMaxnum(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 先保存后更新
		try {
			Map<String, Object> dataMap = paraMap;
			this.service.update(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		StringBufferProxy sql = new StringBufferProxy();
		// 已经发布且有效的金刚区默认数据
		sql.appendSingle("areacode = '{0}' and publish = {1} and enabled = {2}",
				SystemConst.AppAreaType.corearea, SystemConst.PublishState, SystemConst.Enabled_Yes);
		List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList = this.service.queryByWhere(sql.toString());
		if(appAreaInitializationConfigEntityList.size() != 1){
			throw new BusinessException("未找到金刚区发布数据");
		}else{
			// 处理用户信息表金刚区最大数强制更新
			boolean res = this.service.updateForceAppUserInfoCoreareaMaxnum(appAreaInitializationConfigEntityList);
			if(res == true){
				return ResponseResult.ok("更新成功");
			}
		}
		throw new BusinessException("更新失败");
	}


	/**
	 * @Description:    用户信息表最近使用最大数强制更新
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           2/1/2023 下午8:14
	 * @Version:        1.0
	 **/
	@Transactional
	@PutMapping(value = "/updateForceAppUserInfoRecentlyusedareaMaxnum")
	public ResponseResult<Object> updateForceAppUserInfoRecentlyusedareaMaxnum(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 先保存后更新
		try {
			Map<String, Object> dataMap = paraMap;
			this.service.update(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		StringBufferProxy sql = new StringBufferProxy();
		// 已经发布且有效的最经使用默认数据
		sql.appendSingle("areacode = '{0}' and publish = {1} and enabled = {2}",
				SystemConst.AppAreaType.recentlyusedarea, SystemConst.PublishState, SystemConst.Enabled_Yes);
		List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList = this.service.queryByWhere(sql.toString());
		if(appAreaInitializationConfigEntityList.size() != 1){
			throw new BusinessException("未找到最近使用发布数据");
		}else{
			// 处理用户信息表最近使用最大数强制更新
			boolean res = this.service.updateForceAppUserInfoRecentlyusedareaMaxnum(appAreaInitializationConfigEntityList);
			if(res == true){
				return ResponseResult.ok("更新成功");
			}
		}
		throw new BusinessException("更新失败");
	}

    /**
     * @Description:    用户信息表一级目录排序强制更新
     * @Author:         wuyuyang
     * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date:           3/1/2023 下午8:02
     * @Version:        1.0
     **/
	@Transactional
	@PutMapping(value = "/updateForceAppUserInfoFirstleveldirectory")
	public ResponseResult<Object> updateForceAppUserInfoFirstleveldirectory(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 先保存后更新
		try {
			Map<String, Object> dataMap = paraMap;
			this.service.update(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		StringBufferProxy sql = new StringBufferProxy();
		// 已经发布且有效的一级目录默认值数据
		sql.appendSingle("areacode = '{0}' and publish = {1} and enabled = {2}",
				SystemConst.AppAreaType.firstleveldirectory, SystemConst.PublishState, SystemConst.Enabled_Yes);
		List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList = this.service.queryByWhere(sql.toString());
		if(appAreaInitializationConfigEntityList.size() != 1){
			throw new BusinessException("未找到一级目录发布数据");
		}else{
			// 处理用户信息表一级目录强制更新
			boolean res = this.service.updateForceAppUserInfoFirstleveldirectory(appAreaInitializationConfigEntityList);
			if(res == true){
				return ResponseResult.ok("更新成功");
			}
		}
		throw new BusinessException("更新失败");
	}


    /**
     * @Description:    处理一级目录更新
     * @Author:         wuyuyang
     * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date:           28/2/2023 下午5:00
     * @Version:        1.0
     **/
	@GetMapping(value = "/changeModulePosition")
	public ResponseResult<Object> changeModulePosition(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
//			Map<String, Object> dataMap = paraMap;
//			String code =ConvertUtil.convertToString(paraMap.get("code"));
//			String name =ConvertUtil.convertToString(paraMap.get("name"));
//			String index =ConvertUtil.convertToString(paraMap.get("index"));
//			String changeType =ConvertUtil.convertToString(paraMap.get("changeType"));
			// 更新用户数据
			this.service.updateUserinfo(paraMap);
			return ResponseResult.ok("更新成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}

	}
}

